<template>
  <!--餐厅支出-->
  <BasicModal :title="title" :width="'95%'" @register="registerModal" @ok="handleSubmit" @cancel="handleClose"
              :destroyOnClose="true" :canFullscreen="false" :centered="true"
              :bodyStyle="{height:'calc(100vh - 120px)', overflowY:'hidden'}"
  >
    <div class="jeecg-basic-table jeecg-basic-table-form-container" style="margin-top: -10px">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">
          
          <a-col flex="340px">
            <a-form-item label="采购日期" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '250px' } }">
              <a-date-picker
                v-model:value="queryParam.beginDate"
                :disabled-date="disabledStartDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 120px"
              /> ~
              <a-date-picker
                v-model:value="queryParam.endDate"
                :disabled-date="disabledEndDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 120px"
              />
            </a-form-item>
          </a-col>

          <a-col flex="125px">
            <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" >
              <a-select name="status" id="status" v-model:value="queryParam.status" :showArrow="false" :allowClear="true" placeholder="全部">
                <a-select-option value="0">未导入</a-select-option>
                <a-select-option value="1">已导入</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="190px">
            <a-form-item label="入库仓库" :label-col="{ style: { width: '70px' } }">
              <a-input placeholder="" v-model:value="queryParam.warehouseName" ></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="180px">
            <a-form-item label="供应商" :label-col="{ style: { width: '60px' } }">
              <a-input placeholder="" v-model:value="queryParam.areaName" ></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="180px">
            <a-form-item label="物品名称" :label-col="{ style: { width: '70px' } }">
              <a-input placeholder="" v-model:value="queryParam.materialName" ></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="220px">
            <a-form-item label="金额" :label-col="{ style: { width: '50px' } }" :wrapper-col="{ span: 17 }">
              <a-input type="text" v-model:value="queryParam.beginJe" style="width: 60px" @blur="onBlur"/> -
              <a-input type="text" v-model:value="queryParam.endJe"  style="width: 60px"/>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="width:100; margin-right: 0px;">
            <span style="float: right; overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" color="success" preIcon="ant-design:search" @click="searchQuery" class="mr-10px">查询</a-button>
              <j-upload-button type="primary" color="warning" preIcon="ant-design:import-outlined" @click="onImportXls" :disabled="selectedRowKeys.length > 0">导入</j-upload-button>
              <a-button type="primary" color="error" preIcon="ant-design:delete-twotone" @click="handleDelete" class="ml-10px" :disabled="selectedRowKeys.length <= 0"> 删除 </a-button>
            </span>
          </a-col>
        </a-row>

      </a-form>
    </div>

    <!--引用表格 :rowSelection="rowSelection"-->
    <BasicTable @register="registerTable" :loading="loading" :rowSelection="rowSelection"></BasicTable>
    <!-- table区域-end v-auth="'business:delete'"-->

    <SelectModal @register="registerSelectModal" @success="searchQuery"></SelectModal>

    <!--底部操作部分-->
    <template #insertFooter>
      <view style="float: left; height: 28px; line-height: 28px">已选中 {{selectedRowKeys.length}} 条</view>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch, toRaw } from "vue";
import { BasicColumn, BasicTable } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { BasicModal, useModal, useModalInner } from "/@/components/Modal";
import { openAccountList } from "/@/views/full/invoice/types/invoice.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { momentSearchQueryDate } from "/@/utils/dateUtil";
import { render } from "/@/utils/common/renderUtils";
import { list, selectSubmit, batchDelete, getImportUrl } from '/@/views/cater/purchase/Purchase.api';

const { createMessage: $message } = useMessage();
import moment from 'dayjs'
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import SelectModal from "/@/views/full/invoice/modules/openAccountGridSelectModal.vue";

const isUpdate = ref(true);
const $businessId = ref("");
//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const queryParam = reactive<any>({
  beginDate:moment().add(-1, 'month').startOf('month').format('YYYY-MM-DD'),
  endDate: moment(new Date()).endOf("month").format("YYYY-MM-DD"),
  status: '0'
});
let type = ref("");
let title = ref("");
//表单赋值
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  title.value = "餐厅支出" + " - " + data.travelLine + " - " + data.orderId
  queryParam.businessId = data.businessId;
  $businessId.value = data.businessId;
  setSelectedRowKeys([]);
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}

//--金额-------------------------------------------------------
// '.' at the end or only '-' in the input box.
const onBlur = (inputValue) => {

};

//初始化 -------------------------------------------------------------
function searchQuery() {
  setSelectedRowKeys([]);
  setProps({searchInfo:toRaw(queryParam)});
  reload()
}

function searchReset() {
  setSelectedRowKeys([]);
  Object.assign(queryParam, {warehouseName: '', areaName: '', billNo: ''});
  searchQuery();
}

function handleSummary(tableData: Recordable[]) {
  redoHeight();
  const res = getRawDataSource()
  return res.summary || [];
}

//订单列表 - 状态转译
const statusFmt = ({text}: { text: any }) => {
  if (!text) {
    return
  }
  const color = text == '0' ? 'green' : text == '1' ? 'red' : 'gray';
  return render.renderTag(render.renderDict(text, 'purchaseStatus'), color)
}

//订单列表 - 表头
const columns: BasicColumn[] = [
  { title: '状态', dataIndex: 'status', width:40, customRender: statusFmt},
  { title: '入库仓库', dataIndex: 'warehouseName', width:150, align:'left', },
  { title: '供应商', dataIndex: 'areaName', width:150, align:'left', },
  { title: '物料名称', dataIndex: 'materialName', width:60, align:'left', },
  { title: '物料类别', dataIndex: 'materialType', width:60, align:'left', },
  { title: '上级物料', dataIndex: 'materialParentType', width:60, align:'left', },
  { title: '单价', dataIndex: 'univalence', width:30, align:'right' },
  { title: '数量', dataIndex: 'qty', width:30 },
  { title: '单位', dataIndex: 'sku', width:30 },
  { title: '金额', dataIndex: 'price', width:30, align:'right' },
  { title: '采购日期', dataIndex: 'purchaseDate', width:50 },
];

// 列表页面公共参数、方法
const loading     = ref<boolean>(false);
const dataSource  = ref<any[]>([]);
const summaryData = ref<any[]>([]);
const {prefixCls, tableContext, onImportXls} = useListPage({
  designScope: 'open-account-excel',
  tableProps: {
    api: list,
    columns: columns,
    showIndexColumn: false,    //行号
    clickToRowSelect: true,    //点击选择
    showActionColumn: false,
    showTableSetting: false,
    useSearchForm: false,
    showSummary: false,
    resizeHeightOffset: 65,
    pagination: {
      current: 1,
      pageSize: 100,
      pageSizeOptions: ['100', '300', '500'],
    },
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
  },
  importConfig: {
    url: getImportUrl
  },
})

// 注册table数据
const [registerTable, {reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight}, {rowSelection, selectedRowKeys, selectedRows}] = tableContext

// 数据导入 - 勾选 -------------------------
const [registerSelectModal, { openModal: openSelectModal }] = useModal();
async function handleSubmit() {
  //1、获取被选中的行信息
  let rows = selectedRows.value;
  if (rows.length <= 0) {
    $message.warning("请勾选")
    return false
  }

  //2、判断选中的单位是否是同一家
  var ids = ''
  for (var i = 0; i < rows.length; i++) {
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }

  var params = {ids:ids, businessId: $businessId.value, type: type.value}
  //console.info("params@@@", queryParam)
  //openSelectModal(true, params);

  await selectSubmit(params).then((res) => {
    try {
      if (res.success != true) {
        $message.warning(res.message);
        return false;
      } else {
        $message.success("操作成功！");
        closeModal();
        emit("success");
      }
    } catch (e) {
      alert(e);
      return false;
    }
  })
}

const emit = defineEmits(['success', 'register']);
function handleClose() {
  console.info("handleClose")
  emit("success");
}

/**
* 批量删除事件
*/
async function handleDelete() {
  await batchDelete({ids: selectedRowKeys.value}, searchQuery);
}

</script>

<style lang="less" scoped>

</style>
